package cn.chencq.gdt;

import java.util.Calendar;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicInteger;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.chencq.gdt.utils.GdtConfig;
import cn.chencq.gdt.utils.MoblieInfoCache;
import cn.chencq.gdt.utils.ThreadPoolUtil;
import cn.chencq.gdt.utils.Utils;
import cn.chencq.gdt.vo.Bussiness;
import cn.chencq.gdt.vo.Gdt;
import cn.chencq.gdt.vo.Mobile;
import cn.chencq.gdt.vo.ProxyIp;
import cn.chencq.gdt.vo.ProxyQueue;

import com.limei.adplatform.redis.cluster.RedisClusterFactory;

public class Main {
	private static final Logger logger = LoggerFactory.getLogger(Main.class);

	// 记录执行数
	private static AtomicInteger number = new AtomicInteger(0);

	public static void main(String[] args) {
		// 初始化redis
		RedisClusterFactory.init("redis_7379.xml");
		// 获取所有广告位
		List<Gdt> gdtList = GdtConfig.getList();

		while (true) {
			// 获取代理ip
			ProxyIp proxy = null;
			int retry = 0;
			try {
				do {
					proxy = ProxyQueue.pop();
					if (retry > 10) {
						throw new RuntimeException("获取代理IP数据异常");
					}
					retry++;
				} while (proxy == null);

				// 通过代理ip执行业务逻辑
				Set<Future<Boolean>> sf = new HashSet<Future<Boolean>>();
				for (Gdt gdt : gdtList) {
					String rid = Utils.generateRID();
					Mobile mobile = null;
					int mTry = 0;
					do {
						mobile = MoblieInfoCache.getOne(gdt.getC_os());
						if (mTry > 10) {
							throw new RuntimeException("获取mobile数据异常");
						}
						mTry++;
					} while (mobile == null);

					logger.info("rid:{},gdt:{},proxy:{},mobile:{},num:{}", rid, gdt.toString(), proxy.toString(), mobile.toString(), number.incrementAndGet());
					Bussiness bussiness = new Bussiness(rid, gdt, proxy, mobile);
					sf.add(ThreadPoolUtil.submit(bussiness));
				}

				for (Future<Boolean> futher : sf) {
					try {
						futher.get();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}

				// 根据时间段来调整执行的频率
				sleep();
			} catch (RuntimeException ex) {
				logger.info("main throw exception:{}", ex);
			}
		}
	}

	public static void sleep() {
		Calendar c = Calendar.getInstance();
		int hour = c.get(Calendar.HOUR_OF_DAY);
		try {
			if (hour < 8) {// 0~7点执行频率减慢,休息时间加长
				Thread.sleep(1000 * new Random().nextInt(60 * 5));
			} else if (hour > 21) {// 晚上9点之后执行频率
				Thread.sleep(1000 * new Random().nextInt(60 * 2));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
